import qs from 'kuan-utils/lib/qs'
import encrypt from './encrypt' // 加密对接
import authority from '../authority'
import { showErr } from '../feedBack'

// 接口域名
const isDev = process.env.NODE_ENV === 'development'
const devBase = 'https://shan.weddingee.com'
const prodBase = 'https://www.shangehun.com'
export const baseUrl = isDev ? devBase : prodBase

export default ({ url, data = {}, params = {}, method = 'get' }) => {
  const now = Date.now() / 1000
  const { token, regionCode } = authority.get() || {}

  const header = {
    'content-type': 'application/json',
    'X-Halo-App': 'wedding-miniapp',
    'X-Halo-Region': regionCode || 310100,
    'Http-Request-Halo-Time': now,
    'Http-Request-Halo-Sign': encrypt({ ...params, ...data, time: now })
  }

  if (token) header.Authorization = `Bearer ${token}`

  return new Promise(async (resolve, reject) => {
    let search = qs.stringify(params)
    const finalUrl = url.startsWith('http') ? url : `${baseUrl}${url}`
    wx.request({
      url: finalUrl + (search ? `?${search}` : search),
      data,
      method: method.toUpperCase(),
      header,
      success(result) {
        const { iRet, data, info } = result.data
        if (iRet !== 1) {
          if (result.statusCode !== 401) showErr(info)
          reject(result)
        } else {
          resolve(data)
        }
      },
      fail(e) {
        showErr('网络异常')
        reject(e)
      }
    })
  })
}
